Vue Js Modal Close when Click Outside:In Vue.js, you can close a modal when clicking outside of it by utilizing event listeners and conditional rendering. First, you need to add an event listener to the document that listens for a click event. Within the event handler, you can check if the clicked element is outside the modal by comparing it with the modal’s DOM element. If it is outside, you can close the modal by setting a data property that controls its visibility. To achieve this, you can use the v-if or v-show directives to conditionally render the modal based on the data property value.
How do I close modal after clicking outside in Vue Js?
This Vue.js code demonstrates a modal functionality that closes when clicking outside of it. Initially, the modal is hidden (v-if="isModalOpen"
), and clicking the “Open Modal” button sets isModalOpen
to true, displaying the modal.
When opening the modal, the openModal
method is triggered, which sets isModalOpen
to true and attaches a mouseup
event listener to the document using addEventListener
. The event listener is defined as closeModalOnClickOutside
.
In the closeModalOnClickOutside
method, it checks if the clicked element (event.target
) is not inside the modal (!modal.contains(event.target)
), and if so, it calls the closeModal
method to close the modal.
The closeModal
method sets isModalOpen
to false and removes the mouseup
event listener from the document using removeEventListener
Vue Js Modal Close When Click Outside Example
<div id="app">
<button @click="openModal" class="open-modal">Open Modal</button>
<div class="modal" v-if="isModalOpen">
<div class="modal-content" ref="modalRef">
<h3>Vue Js Close Modal when click outside</h3>
<!-- Modal content here -->
<button class="close-button" @click="closeModal">Close</button>
</div>
</div>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
isModalOpen: false
};
},
methods: {
openModal() {
this.isModalOpen = true;
// Attach the mouseup event listener to the document
document.addEventListener('mouseup', this.closeModalOnClickOutside);
},
closeModal() {
this.isModalOpen = false;
// Remove the mouseup event listener from the document
document.removeEventListener('mouseup', this.closeModalOnClickOutside);
},
closeModalOnClickOutside(event) {
const modal = this.$refs.modalRef;
if (!modal.contains(event.target)) {
this.closeModal();
}
}
}
});
</script>